package com.dyrnq.seckill.controller;

import com.dyrnq.seckill.service.CleanDataService;
import com.dyrnq.seckill.service.ISeckillSvc;
import com.dyrnq.seckill.service.impl.RedPacketService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api")
@RequiredArgsConstructor
public class ApiController implements ApplicationContextAware {
    private final CleanDataService cleanDataService;
    private final RedPacketService redPacketService;
    private ApplicationContext context;


    @ResponseBody
    @RequestMapping("/red/clean")
    public Result<String> redClean(long red_packet_id, int total_amount, int total_packet) {
        redPacketService.cleanAndRefresh(red_packet_id, total_amount, total_packet);
        return Result.success("");
    }

    @ResponseBody
    @RequestMapping("/red/occ")
    public Result<String> grabRedPacket_occ(long red_packet_id, long user_id) {
        redPacketService.grabRedPacket_occ(red_packet_id, user_id);
        return Result.success("");
    }

    @ResponseBody
    @RequestMapping("/{ver}")
    public Result<String> doSeckill(@PathVariable String ver, long goods_id, long user_id) {
        ISeckillSvc svc = this.getBean("seckillSvc_" + ver);
        svc.doSeckill(goods_id, user_id);
        return Result.success("");
    }


    @ResponseBody
    @RequestMapping("/one/{ver}")
    public Result<String> doSeckill_one(@PathVariable String ver, long goods_id, long user_id) {
        ISeckillSvc svc = this.getBean("seckillSvc_" + ver);
        svc.doSeckill_1user1order(goods_id, user_id);
        return Result.success("");
    }


    @ResponseBody
    @RequestMapping("/redis_one/{ver}")
    public Result<String> doSeckill_redis_one(@PathVariable String ver, long goods_id, long user_id) {
        ISeckillSvc svc = this.getBean("seckillSvc_" + ver);
        svc.doSeckill_1user1order_redis(goods_id, user_id);
        return Result.success("");
    }

    /**
     * 重置数据库数据，以及重置redis缓存数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/clean")
    public Result<String> clean() {
        cleanDataService.clean();
        return Result.success("");
    }

    protected <T> T getBean(String name) {
        return (T) getApplicationContext().getBean(name);
    }

    protected ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
